package com.saltedfish.tool.ui.flag

import android.Manifest
import android.os.Bundle
import android.os.Handler
import android.text.TextUtils
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.Room
import androidx.room.RoomDatabase
import cn.droidlover.xdroidmvp.base.SimpleListener
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.imageloader.ILFactory
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.mvp.XFragment
import cn.droidlover.xdroidmvp.popwindow.AlertButtonDialog
import cn.droidlover.xdroidmvp.router.Router
import cn.droidlover.xdroidmvp.util.AppUtil
import com.blankj.rxbus.RxBus
import com.saltedfish.tool.R
import com.saltedfish.tool.constant.StringConstant
import com.saltedfish.tool.dao.AppDatabase
import com.saltedfish.tool.dao.DayDBDao
import com.saltedfish.tool.dao.SubFlagModelDao
import com.saltedfish.tool.dialog.*
import com.saltedfish.tool.model.*
import com.saltedfish.tool.present.FlagAP
import com.saltedfish.tool.ui.flag.adapter.FlagAdapter
import com.saltedfish.tool.ui.user.LoginActivity
import com.saltedfish.tool.util.*
import com.tencent.wcdb.database.SQLiteCipherSpec
import com.tencent.wcdb.database.SQLiteDatabase
import com.tencent.wcdb.room.db.WCDBOpenHelperFactory
import kotlinx.android.synthetic.main.fragment_flag.*
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class FragmentFlag : XFragment<FlagAP>(), View.OnClickListener {

    companion object {
        fun newInstance(): FragmentFlag {
            return FragmentFlag()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_flag
    }

    override fun initData(savedInstanceState: Bundle?) {
        initRoom()
        cal = Calendar.getInstance()

        BusProvider.getBus().subscribe(context,
                RxBus.Callback<ModelInfo> { modelInfo ->
                    if (modelInfo.updateFlag) {
                        initDataShow()
                        uploadFile()
                        getAllByStatusForProgress()
                        if(modelInfo.flagDone){
                            initFlagDoneDialog(modelInfo.type,modelInfo.title)
                        }


                    }
                })

    }


    private val formatterDay = SimpleDateFormat("yyyy-MM-dd")
    var dayDBDao: DayDBDao? = null
    var subFlagModelDao: SubFlagModelDao? = null

    var cal: Calendar? = null

    /**
     * 获取延期的子目标以及重新添加日程
     */
    private fun getAllByStatusForProgress() {

        Thread{
            var subFlagLists = subFlagModelDao!!.getAllByStatusForProgress("已延期", 1.0f,0)
            if(subFlagLists.size !=0){
                for (item in subFlagLists) {
                    insertDayDBTable(item)
                }
            }
        }.start()
    }

    /**
     * 添加日程
     */
    private fun insertDayDBTable(subFlagModel: SmallTable) {
        if (dayDBDao != null) {
            val weeks: Array<String> = subFlagModel.repeatDay.split(" ").toTypedArray()
            val list: MutableList<String> = ArrayList()
            val today = cal!!.time
            var delayCount = subFlagModel.tick - subFlagModel.tickNum
            var dou = delayCount / weeks.size
            var num = Math.ceil(dou.toDouble())
            cal!!.add(Calendar.DATE, (7 * num).toInt())
            val selectDayDate = cal!!.time
            for (week in weeks) {
                list.addAll(DateUtils.getWeekly(formatterDay.format(today), formatterDay.format(selectDayDate), week))
            }
            for (time in list) {
                val dayTable = DayTable()
                dayTable.day = time
                dayTable.title = subFlagModel.title
                dayTable.fId = subFlagModel.fId
                dayTable.isTick = false
                dayTable.repeatTime = subFlagModel.repeatTime
                dayTable.subId = subFlagModel.subId
                dayTable.createTime = subFlagModel.createTime
                dayDBDao!!.insert(dayTable)
            }
            subFlagModel.delayCount = 1
            subFlagModelDao!!.update(subFlagModel)

        }
    }

    private var uiFlagDoneDialog: UIFlagDoneDialog? = null

    /**
     *  打卡完成弹窗
     */
    private fun initFlagDoneDialog(type: Int, title: String) {

        if (uiFlagDoneDialog == null) {
            uiFlagDoneDialog = UIFlagDoneDialog(context)
        }
        uiFlagDoneDialog!!.updateFlagDone(type, title)
        uiFlagDoneDialog!!.show()
    }


    private fun uploadFile() {
        var  flag = context.getDatabasePath(StringConstant.DbBase)
        var infoDao = database!!.flagInfoDao()
        flagInfoLists = infoDao!!.getAll(false)
        XLog.e("-${flag}---uploadFile--->>$flagInfoLists")
        if (flag.exists()) {
            p.uploadFile(flag.absolutePath)
        }

       // showProgressDialog()
//        mHandler.postDelayed(Runnable {
//
//        }, 3000)

        //储存下载文件的目录
//        val dir = File(StringConstant.STORAGE_DIR)
//        if (!dir.exists()) {
//            dir.mkdirs()
//        }
//        val flag = File(dir, StringConstant.DbBase)

//        XLog.e("---flag-->>$flag")


    }


    override fun loadData() {
        super.loadData()
        showTopData()
    }

    //显示顶部数据资源
    private fun showTopData() {
        ViewClickUtils.setViewClick(this, iv_user)
        ViewClickUtils.setViewClick(this, iv_create_flag)
        ViewClickUtils.setViewClick(this, tips_flag_cjzmb)
        ViewClickUtils.setViewClick(this, tips_flag_ckfxq)
        ViewClickUtils.setViewClick(this, tips_flag_ckzxq)
        initDataShow()

    }

    override fun newP(): FlagAP? {
        return FlagAP()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_user -> {
                initUserView()
            }
            R.id.iv_create_flag -> {
                checkStoragePermission()
            }
            R.id.tips_flag_cjzmb -> {
                tips_flag_cjzmb.visibility = View.GONE
                SharePreferceUtils.setString("tips_flag_cjzmb", "tips_flag_cjzmb")
            }
            R.id.tips_flag_ckfxq -> {
                tips_flag_ckfxq.visibility = View.GONE
                SharePreferceUtils.setString("tips_flag_ckfxq", "tips_flag_ckfxq")
            }
            R.id.tips_flag_ckzxq -> {
                tips_flag_ckzxq.visibility = View.GONE
                SharePreferceUtils.setString("tips_flag_ckzxq", "tips_flag_ckzxq")
            }
        }
    }

    //检查相关权限
    private fun checkStoragePermission() {
        if (
                rxPermissions.isGranted(Manifest.permission.READ_CALENDAR)
                && rxPermissions.isGranted(Manifest.permission.WRITE_CALENDAR)
                && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
                && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        ) {
            initCreateFalgView()
        } else {
            rxPermissions.request(
                    Manifest.permission.READ_CALENDAR,
                    Manifest.permission.WRITE_CALENDAR,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
            ).subscribe { t ->
                if (t) {
                    initCreateFalgView()
                }
            }.isDisposed
        }

    }

    override fun onResume() {
        super.onResume()
        val USER_IMAGE = SharePreferceUtils.getString(User.USER_IMAGE)
        ILFactory.getLoader().loadCircle(USER_IMAGE, iv_user, null)

    }

    private var  dialog : UIUserDialog? =null
    private var database: AppDatabase? = null

    private var  outDialog : UILogoutDialog? =null
    private var  sugDialog : UISuggestionDialog? =null
    private var  createFlagDialog : UICreateFlagDialog? =null
    private val mHandler = Handler()

    /**
     * 创建Flag
     */
    private fun initCreateFalgView() {

//        if (createFlagDialog == null) {
            createFlagDialog = UICreateFlagDialog(context, database)
            createFlagDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {
//                    if (type == "save") {
//                        initDataShow()
//                        createFlagDialog!!.dismiss()
//                    }
                }
            })
//        }
        createFlagDialog!!.setOnKeyBackListener(false)
        createFlagDialog!!.show()
        mHandler.postDelayed({
            AppUtil.showSoftInput(context)
        }, 500)

    }

    /**
     *退出登录
     */
    private fun initLogoutView() {
        if (outDialog == null) {
            outDialog = UILogoutDialog(context)
            outDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {
                    if (type == "logout") {
                        cancelAllData()
                    }
                }
            })
        }

        outDialog!!.show()

    }



        /**
     *
     */
    private fun initSuggestionView() {
        if (sugDialog == null) {
            sugDialog = UISuggestionDialog(context)
        }
        sugDialog!!.show()

    }

    /**
     *用户中心
     */
    private fun initUserView() {
        if (dialog == null) {
            dialog = UIUserDialog(context)
            dialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {
                    if (type == "rel_logout") {
                        initLogoutView()
                    } else if (type == "rel_suggest") {
                        initSuggestionView()
                    } else if (type == "userService") {
                        initServiceView("userService")
                    } else if (type == "userSecret") {
                        initServiceView("userSecret")
                    } else if (type == "outCancel") {
                        outCancelDialog()
                    }
                }
            })
        }

        dialog!!.show()

    }

    /**
     * 注销账号
     */
    private fun outCancelDialog() {
        val dialog = AlertButtonDialog(context)
        dialog.builder()
        dialog.setTitle("注销账号")
        dialog.setMsg("   感谢您一直以来的陪伴，并让咸鱼Flag见证了您的成长！注销账号后，您创建的所有flag、子目标及所有完成记录将被删除且无法恢复!")
        dialog.setPositiveButton("确认注销"
        ) {
            outCancelDb()
        }
        dialog.setNegativeButton("还是算了 "
        ) {

        }
        dialog.show()
    }

    private fun outCancelDb() {
        if(database!=null){
             var  dayDBDao = database!!.dayDBDao()
            var   subFlagDao = database!!.subFlagDao()
            var  flagInfoDao = database!!.flagInfoDao()
            var  calenderDao = database!!.calenderDao()

            dayDBDao.deleteAll()
            subFlagDao.deleteAll()
            flagInfoDao.deleteAll()
            calenderDao.deleteAll()

          //  initDataShow()
            cancelAllData()

        }


    }

  private fun cancelAllData(){
      var  flag = context.getDatabasePath(StringConstant.DbBase)
      if (flag.exists()) {
          p.uploadFile(flag.absolutePath)
      }
      var infoDaos = database!!.subFlagDao()
      var subFlagLists = infoDaos!!.all
      for (item in subFlagLists) {
          CalendarReminderUtils.deleteCalendarEvent(context, item.subId)
      }
      mHandler.postDelayed(Runnable {
          val dir = File(StringConstant.STORAGE_DIR)
          if (dir.exists()) {
              FileSizeUtil.deleteFiles(dir)
          }
          if (flag.exists()) {
              SQLiteDatabase.deleteDatabase(flag)
          }
      }, 100)
      User.getInstance().logoutSuccess()
      Router.newIntent(context).to(LoginActivity::class.java).launch()
      context.finish()
  }

    private var  serviceDialog : UIServiceDialog? =null

    /**
     *
     */
    private fun initServiceView(type: String) {
        if (serviceDialog == null) {
            serviceDialog = UIServiceDialog(context)
        }
        serviceDialog!!.initService(type)
        serviceDialog!!.show()

    }

    private var linearLayoutManager: LinearLayoutManager? = null
    private var adapter: FlagAdapter? = null
    private var flagInfoLists: MutableList<FlagTable> = ArrayList()

    private fun  initDataShow(){
        mLinearHaveFlag.visibility = View.VISIBLE
        tips_flag_cjzmb.visibility = View.GONE
        tips_flag_ckzxq.visibility = View.GONE
        tips_flag_ckfxq.visibility = View.GONE

        flagInfoLists.clear()
        if(database !=null){
           var infoDao = database!!.flagInfoDao()
            flagInfoLists = infoDao!!.getAll(false)
            adapter = FlagAdapter(flagInfoLists)
            mRecyclerView.adapter = adapter
//            XLog.e("---123---"+flagInfoLists)
            if(flagInfoLists.size !=0){
                mLinearHaveFlag.visibility = View.GONE
                linearLayoutManager = LinearLayoutManager(context)
                mRecyclerView.layoutManager = linearLayoutManager
                adapter!!.setSubFlagModelDao(database)

                //创建第一个flag出现的引导页
               var tipFlag =  SharePreferceUtils.getString("tips_flag_cjzmb")
                if(TextUtils.isEmpty(tipFlag)){
                    tips_flag_cjzmb.visibility = View.VISIBLE
                }

                var infoDaos = database!!.subFlagDao()
                var subFlagLists = infoDaos!!.all
                if(subFlagLists.size !=0){
                    var tipFlags =  SharePreferceUtils.getString("tips_flag_ckfxq")
                    if(TextUtils.isEmpty(tipFlags)){
                        tips_flag_ckfxq.visibility = View.VISIBLE
                        tips_flag_ckzxq.visibility = View.VISIBLE
                    }
                }

                adapter!!.setListener(object : SimpleListener<String>() {
                    override fun onClick(flagId: String) {
                        initCreateSonFalgView(flagId)
                    }

                    override fun onClick(flagId: String, str: String) {
                        Router.newIntent(context)
                            .putString("flagId", flagId)
                            .to(FlagDetailActivity::class.java).launch()
                    }
                })
            }

        }


    }

    private var  createSonFlagDialog : UICreateSonFlagDialog? =null

    /**
     * 创建子目标
     */
    private fun initCreateSonFalgView(flagId: String) {

      //  if (createSonFlagDialog == null) {
            createSonFlagDialog = UICreateSonFlagDialog(context, flagId, database)
            createSonFlagDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {

                }
            })
     //   }
        createSonFlagDialog!!.updateFlag(null, flagId)
        createSonFlagDialog!!.show()

        mHandler.postDelayed(Runnable {
            AppUtil.showSoftInput(context)
        }, 500)


    }


    private fun initRoom() {

        val cipherSpec = SQLiteCipherSpec()
            .setPageSize(4096)
            .setKDFIteration(64000)
        val factory =
            WCDBOpenHelperFactory() //  .passphrase("passphrase".getBytes())  // passphrase to the database, remove this line for plain-text
                .cipherSpec(cipherSpec) // cipher to use, remove for default settings
                // .writeAheadLoggingEnabled(false)       // enable WAL mode, remove if not needed
                .asyncCheckpointEnabled(true) // enable asynchronous checkpoint, remove if not needed
        database = Room.databaseBuilder(
                context,
                AppDatabase::class.java, StringConstant.DbBase
        )
            .allowMainThreadQueries()
            .setJournalMode(RoomDatabase.JournalMode.TRUNCATE)
            .openHelperFactory(factory) // specify WCDBOpenHelperFactory when opening database
            .build()
        dayDBDao = database!!.dayDBDao()
        subFlagModelDao = database!!.subFlagDao()


    }

}

